﻿using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace Gp.Scripts.Editor
{
    [TopToolbarDrawer(order: 9)]
    public class SceneSwitchDrawer : ITopToolbarDrawer
    {
        private const string HOME_PATH = "Assets/_Home/";
        private const string MAIN_PATH = "Assets/AAA/Scenes/";
        private List<string> _cachedScenes = new();
        private List<string> _displayScenes = new();

        public SceneSwitchDrawer()
        {
            ReBuildCachedScene();
            EditorApplication.projectChanged += ReBuildCachedScene;
        }

        private void ReBuildCachedScene()
        {
            _cachedScenes.Clear();

            string[] sceneAssets = AssetDatabase.FindAssets("t:Scene", new[] {HOME_PATH, MAIN_PATH});
            // 获取全路径
            for (int i = 0; i < sceneAssets.Length; i++)
            {
                string guid = sceneAssets[i];
                string path = AssetDatabase.GUIDToAssetPath(guid);
                if (path.StartsWith(MAIN_PATH))
                {
                    _cachedScenes.Add(path);
                    _displayScenes.Add(path.Replace(MAIN_PATH, "Main"));
                }
                else if (path.StartsWith(HOME_PATH))
                {
                    var arr = path.Replace(HOME_PATH, string.Empty).Split("/");
                    if (arr.Length < 2) continue;
                    _cachedScenes.Add(path);
                    _displayScenes.Add($"{arr[0]}/{arr[^1]}");
                }
            }
        }

        public void OnToolbarGUI()
        {
            GUILayout.FlexibleSpace();

            if (GUILayout.Button("切换场景"))
            {
                GenericMenu menu = new GenericMenu();

                for (int i = 0; i < _displayScenes.Count; i++)
                {
                    // 因为闭包，所以需要用临时变量
                    int temp = i;
                    string displayPath = _displayScenes[i];
                    menu.AddItem
                    (
                        new GUIContent(displayPath),
                        false,
                        () =>
                        {
                            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                            {
                                EditorSceneManager.OpenScene(_cachedScenes[temp], OpenSceneMode.Single);
                            }
                        }
                    );
                }

                menu.ShowAsContext();
            }
        }
        
    }
}